package org.linphone.activity;

import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import com.android.volley.Request.Method;
import com.android.volley.AuthFailureError;
import com.android.volley.RequestQueue;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnClickListener;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import com.leehuubsd.yiyanzb.R;
import com.umeng.analytics.MobclickAgent;

public class New_Login_vCode extends Activity {

	static ProgressDialog m_Dialog;

	String ProgressMsg = "";
	MyCount mc;
	AlertDialog dlg;
	private String OEMID, Userpwd, UserPhone;
	private EditText Uid, UpwdEt;
	private Button btn_pay;
	private TextView textView1;
	private RelativeLayout login_yy;
	public void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
	}

	public void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.laynewlogin_vcode);
		Intent intent = getIntent();
		UserPhone = intent.getStringExtra("UserPhone");
		Userpwd = intent.getStringExtra("Upwd");
		OEMID = getResources().getString(R.string.oem);
		login_yy = (RelativeLayout) findViewById(R.id.login_yy);
		Uid = (EditText) findViewById(R.id.editText1_ID);
		UpwdEt = (EditText) findViewById(R.id.editText3_ID);
		btn_pay = (Button) findViewById(R.id.btn_pay);
		Uid.setText(UserPhone);
		Uid.setKeyListener(null);
		time = new TimeCount(60000, 1000);// 构造CountDownTimer对象
	}

	public void back(View v) {
		finish();
	}

	public void Do_Reg001(View v) {
		btn_pay.setClickable(false);
		String Phones = Uid.getText().toString();
		if (!TextUtils.isEmpty(Phones)) {

			String path = getResources().getString(R.string.http)
					+ "/api/Account/GetValidateCode?SrcPhone=[手机]&proxyId=[代理]&Type=[类型]"
							.replace("[手机]", UserPhone).replace("[代理]", OEMID)
							.replace("[类型]", "1");
			getdate(path.toString());
		} else {
			Show_Toast("请填写手机号");
		}
	}

	public void Do_Reg002(View v) {
		btn_pay.setClickable(false);
		login_yy.setClickable(false);
		String Phones = Uid.getText().toString();
		if (!TextUtils.isEmpty(Phones)) {

			String path = getResources().getString(R.string.http)
					+ "/api/Account/GetValidateCode?SrcPhone=[手机]&proxyId=[代理]&Type=[类型]"
							.replace("[手机]", UserPhone).replace("[代理]", OEMID)
							.replace("[类型]", "2");
			getdate(path.toString());
		} else {
			Show_Toast("请填写手机号");
		}
	}

	// get请求
	private void getdate(String path) {
		RequestQueue queue = Volley.newRequestQueue(this);
		String url = path;
		StringRequest request = new StringRequest(Method.GET, url,
				new Listener<String>() {
					@Override
					public void onResponse(String response) {
						Log.i("LOL", response);
						parserToObject(response);
					}
				}, new ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError arg0) {
						Log.i("log", "!!!!onErrorResponse" + arg0.toString());
						Toast.makeText(getApplicationContext(), "网络错误！",
								Toast.LENGTH_SHORT).show();
						btn_pay.setClickable(true);
						login_yy.setClickable(true);
					}
				});
		queue.add(request);
	}

	protected void parserToObject(String json) {
		JSONObject object;
		JSONTokener jsonTokener = new JSONTokener(json);
		try {
			JSONObject person = (JSONObject) jsonTokener.nextValue();
			if (person.getBoolean("success")) {
				Toast.makeText(getApplicationContext(), "获取验证码成功，请稍后！",
						Toast.LENGTH_SHORT).show();
				time.start();// 开始计时
			} else {
				Toast.makeText(getApplicationContext(),
						person.getString("message"), Toast.LENGTH_SHORT).show();
				btn_pay.setClickable(true);
				login_yy.setClickable(true);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			Toast.makeText(getApplicationContext(), "服务器异常！",
					Toast.LENGTH_SHORT).show();
			btn_pay.setClickable(true);
			login_yy.setClickable(true);
			e.printStackTrace();
		}
	}

	private TimeCount time;

	/* 定义一个倒计时的内部类 */
	class TimeCount extends CountDownTimer {
		public TimeCount(long millisInFuture, long countDownInterval) {
			super(millisInFuture, countDownInterval);// 参数依次为总时长,和计时的时间间隔
		}

		@Override
		public void onFinish() {// 计时完毕时触发
			btn_pay.setText("重新获取");
			btn_pay.setClickable(true);
			login_yy.setClickable(true);
		}

		@Override
		public void onTick(long millisUntilFinished) {// 计时过程显示
			btn_pay.setText(millisUntilFinished / 1000 + "秒");
		}
	}

	public void do_login(View v) {

		GetPostDate("/YXBp/dm9zb2Vt/VerificationAccount", UpwdEt.getText()
				.toString());

	}

	public void Show_Dialog(String tit, String txt) {
		Dialog dialog = new AlertDialog.Builder(this)
				.setIcon(R.drawable.ic_launcher).setTitle(tit).setMessage(txt)
				.setPositiveButton("确定", new OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
					}
				}).create();
		dialog.show();

	}

	// HTTP GET
	public static String TryGetUrl(StringBuffer path) {
		HttpResponse httpResponse = null;
		try {
			HttpGet httpGet = new HttpGet(path.toString());
			httpResponse = new DefaultHttpClient().execute(httpGet);
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				String result = EntityUtils.toString(httpResponse.getEntity());
				String str = new String(result.getBytes("UTF-8"));
				return str;
			} else {
				return "x500";
			}
		} catch (Exception e) {
			return "x400";
		}
	}

	class MyCount extends CountDownTimer {

		public MyCount(long millisInFuture, long countDownInterval) {
			super(millisInFuture, countDownInterval);
		}

		public void onFinish() {
			try {
				m_Dialog.dismiss();
			} catch (Exception e) {
			}
		}

		public void onTick(long millisUntilFinished) {
			long a = millisUntilFinished / 1000;
			m_Dialog.setMessage(ProgressMsg + "（" + (30 - a) + " 秒）");
		}
	}

	private void GetPostDate(final String Path, final String Upwd) {

		ProgressMsg = "正在登录，请稍后……";
		m_Dialog = ProgressDialog.show(New_Login_vCode.this, "", ProgressMsg,
				true);
		m_Dialog.setIcon(android.R.drawable.ic_lock_idle_alarm);
		mc = new MyCount(30000, 1000);
		mc.start();
		RequestQueue queue = Volley.newRequestQueue(this);
		StringRequest request = new StringRequest(Method.POST, getResources()
				.getString(R.string.http) + Path, new Listener<String>() {

			@Override
			public void onResponse(String arg0) {
				// TODO Auto-generated method stub
				Log.i("LOL", arg0);
				m_Dialog.dismiss();
				mc.cancel();
				JSONObject object;
				try {
					object = new JSONObject(arg0);
					int i = object.getInt("retCode");
					if (i == 0) {
						Show_Toast("验证成功，请登录");
						finish();
					} else {
						// 请求失败，查看提示内容
						String s = object.getString("exception");
						Toast.makeText(getApplicationContext(),
								s + "(" + object.getInt("retCode") + ")",
								Toast.LENGTH_SHORT).show();
					}

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}, new com.android.volley.Response.ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError arg0) {
				// TODO Auto-generated method stub
				m_Dialog.dismiss();
				mc.cancel();
				Show_Dialog("错误", "服务器忙，请稍后尝试登陆…");
			}
		}) {
			@Override
			protected Map<String, String> getParams() throws AuthFailureError {
				// TODO Auto-generated method stub
				String p = encryptBASE64(UserPhone);
				Map<String, String> map = new HashMap<String, String>();
				map.put("dXNlck5hbWUPQ", p);
				map.put("password", Userpwd);
				map.put("os", "1");
				map.put("proxyId", OEMID);
				map.put("vCode", Upwd);
				return map;
			}
		};
		queue.add(request);
	}

	public void Show_Toast(String str) {
		Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
	}

	public void Prs_Set_String(String Pname, String Pvlaue) {
		SharedPreferences MyPreferences = getSharedPreferences(getResources()
				.getString(R.string.app_spname), Activity.MODE_PRIVATE
				+ +Activity.MODE_WORLD_READABLE + Activity.MODE_WORLD_WRITEABLE);
		SharedPreferences.Editor editor = MyPreferences.edit();
		editor.putString(Pname, Pvlaue);
		editor.commit();
	}

	public void Prs_Set_Bollean(String Pname, Boolean Pvlaue) {
		SharedPreferences MyPreferences = getSharedPreferences(getResources()
				.getString(R.string.app_spname), Activity.MODE_PRIVATE
				+ +Activity.MODE_WORLD_READABLE + Activity.MODE_WORLD_WRITEABLE);
		SharedPreferences.Editor editor = MyPreferences.edit();
		editor.putBoolean(Pname, Pvlaue);
		editor.commit();
	}

	public boolean Prs_Get_Bollean(String Pname, Boolean Pdefvlaue) {
		SharedPreferences settings = getSharedPreferences(getResources()
				.getString(R.string.app_spname), Activity.MODE_PRIVATE
				+ Activity.MODE_WORLD_READABLE + Activity.MODE_WORLD_WRITEABLE);
		return (settings.getBoolean(Pname, Pdefvlaue));
	}

	public String Prs_Get_String(String Pname, String Pdefvlaue) {
		SharedPreferences settings = getSharedPreferences(getResources()
				.getString(R.string.app_spname), Activity.MODE_PRIVATE
				+ Activity.MODE_WORLD_READABLE + Activity.MODE_WORLD_WRITEABLE);
		return (settings.getString(Pname, Pdefvlaue));
	}

	/**
	 * BASE64 加密
	 * 
	 * @param str
	 * @return
	 */
	@SuppressLint("NewApi")
	public String encryptBASE64(String str) {
		if (str == null || str.length() == 0) {
			return null;
		}
		try {
			byte[] encode = str.getBytes("UTF-8");
			// base64 加密

			String s = new String(Base64.encode(encode, 0, encode.length,
					Base64.DEFAULT), "UTF-8");
			String s1 = s.replaceAll("=", "PQ");
			Log.i("LOL", s1);
			return s1;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		return null;
	}
}
